package info.leetcode.answer.Array.foreach;

import java.util.*;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 第三大的数
 * @date 2024/1/29 10:33
 */
public class ThirdMax {
    public static void main(String[] args) {
        int[] nums = {2, 2, 3, 1};
        int result = thirdMax(nums);
        System.out.println(result);
    }

    private static int thirdMax(int[] nums) {
        // 新建一个结果数组
        TreeSet<Integer> resultSet = new TreeSet<>();
        for (int i = 0; i < nums.length; i++) {
            resultSet.add(nums[i]);
            if (resultSet.size() >3){
                resultSet.remove(resultSet.first());
            }
        }

        return resultSet.size() < 3 ? resultSet.last():resultSet.first();
    }
}
